package org.verifictaion.make;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.util.UUID;
import javax.imageio.ImageIO;

public class CaptchaGenerator {

    public static void main(String[] args) {
        String randomString = RandomStringGenerator.generateRandomString(6);
        BufferedImage image = createCaptchaImage(randomString);
        System.out.println(randomString);
        //输出uuid
        String uuid = UUID.randomUUID().toString();
        String imageName = "image_" + uuid + ".jpg";
        saveImage(image, imageName);
    }
    public static BufferedImage createCaptchaImage(String text) {
        int width = 150;
        int height = 60;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) image.getGraphics();

        // 定义一个白色背景
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.drawRect(0, 0, width - 1, height - 1);

        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2d.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g2d.drawLine(x1, y1, x2, y2);
        }
        for (int i = 0; i < text.length(); i++) {
            int angle = random.nextInt(30)-15;
            AffineTransform transform = new AffineTransform();
            transform.rotate(Math.toRadians(angle));
            g2d.setTransform(transform);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Font font = new Font("Arial", Font.BOLD, 24);
            g2d.setFont(font);
            g2d.setColor(Color.BLACK);
            g2d.drawString(String.valueOf(text.charAt(i)), 23*i + 10, 30- angle +5);
        }
        //该函数用于释放Graphics2D对象所占用的资源，包括关闭图形上下文和释放内存。调用该函数后，g2d对象将不再可用，需要重新创建一个新的对象来绘制图形。
        g2d.dispose();
        return image;
    }
    public static void saveImage(BufferedImage image, String fileName) {
        try {
            ImageIO.write(image, "JPEG", Files.newOutputStream(Paths.get(fileName)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}